<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="6">
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-share" v-if="!writeOffForm.id" @click="getBorrowerAndLenderClick()">获取借贷方明细</el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves icon="el-icon-plus" v-if="!writeOffForm.id" @click="addWriteOffFormClick()">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <div style="clean:both"></div>

    <el-container class="el-container">
      <el-main>
        <el-form :rules="writeOffFormRules" ref="writeOffForm" :inline="true" :model="writeOffForm" label-position="left" label-width="90px" class="demo-form-inline">

          <el-form-item label="主体公司" prop="mainCompanyId">
            <el-select v-model="writeOffForm.mainCompanyId" placeholder="请选择主体公司">
              <el-option v-for="company in companyList" :key="company.id" :label="company.name" :value="company.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="单据类型" prop="docType">
            <el-select v-model="writeOffForm.docType" placeholder="请选择单据类型">
              <el-option v-for="shouldPaymentType in shouldPaymentTypeList" :key="shouldPaymentType.id" :label="shouldPaymentType.name" :value="shouldPaymentType.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="单据日期" prop="docDate">
            <el-date-picker class="fsc-input" v-model="writeOffForm.docDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择单据日期"></el-date-picker>
          </el-form-item>

          <el-form-item label="核销日期" prop="auditDate">
            <el-date-picker class="fsc-input" v-model="writeOffForm.auditDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择核销日期"></el-date-picker>
          </el-form-item>

          <el-form-item label="供应商" prop="partnerId">
            <el-select v-model="writeOffForm.partnerId" filterable placeholder="请选择供应商">
              <el-option v-for="partner in partnerList" :key="partner.id" :label="partner.name" :value="partner.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="币种" prop="currencyTypeId">
            <el-select v-model="writeOffForm.currencyTypeId" placeholder="请选择币种">
              <el-option v-for="currencyType in currencyTypeList" :key="currencyType.id" :label="currencyType.name" :value="currencyType.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="会计期间" prop="fiscalPeriod">
            <el-select v-model="writeOffForm.fiscalPeriod" placeholder="请选择会计期间">
              <el-option v-for="fiscalPeriod in fiscalPeriodList" :key="fiscalPeriod.id" :label="fiscalPeriod.name" :value="fiscalPeriod.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="差异金额" prop="differAmt">
            <el-input class="fsc-input" v-model="writeOffForm.differAmt" placeholder="请输入差异金额"></el-input>
          </el-form-item>

          <el-form-item label="差异原因" prop="differReason">
            <el-input class="fsc-input" v-model="writeOffForm.differReason" placeholder="请输入差异原因"></el-input>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input class="fsc-input" v-model="writeOffForm.remark" placeholder="请输入备注"></el-input>
          </el-form-item>

        </el-form>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>借方明细</span>
          </div>
          <div>
            <el-table ref="borrowerFormTable" :data="borrowerWriteOffDetailList" v-loading="listLoading" element-loading-text="加载中" border fit highlight-current-row style="width: 100%;margin-top:5px">
              <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
              <el-table-column label="业务类型">
                <template slot-scope="scope">
                  <div>{{scope.row.writeOffBtId | payBusinessTypeFilter}}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="单据类型" prop="writeOffDtName"></el-table-column>
              <el-table-column align="center" label="单据编号" prop="docCode"></el-table-column>
              <el-table-column align="center" label="可核销金额" prop="money"></el-table-column>
              <el-table-column align="center" label="本次核销金额">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.writeOffAmountOc" placeholder="请输入核销金额"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-minus" @click="removeBorrowerClick(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <div>总金额:{{borrowerMoneyCount}}</div>
          </div>
        </el-card>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>贷方明细</span>
          </div>
          <div>
            <el-table ref="lenderFormTable" :data="lenderWriteOffDetailList" v-loading="listLoading" element-loading-text="加载中" border fit highlight-current-row style="width: 100%;margin-top:5px">
              <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
              <el-table-column label="业务类型">
                <template slot-scope="scope">
                  <div>{{scope.row.writeOffBtId | payBusinessTypeFilter}}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="单据类型" prop="writeOffDtName"></el-table-column>
              <el-table-column align="center" label="单据编号" prop="docCode"></el-table-column>
              <el-table-column align="center" label="可核销金额" prop="money"></el-table-column>
              <el-table-column align="center" label="本次核销金额">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.writeOffAmountOc" placeholder="请输入核销金额"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-minus" @click="removeLenderClick(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <div>总金额:{{lenderMoneyCount}}</div>
          </div>
        </el-card>

        <el-dialog title="获取借贷方明细" :visible.sync="dialogFormVisible" width="45%" @close="closeDialogForm">
          <el-container style="width: 95%">
            <el-main>
              <el-form ref="borrowerForm" :inline="true" :model="writeOffSearch" label-position="left" label-width="90px" class="demo-form-inline">
                <el-form-item label="供应商" prop="partnerId">
                  <el-select v-model="writeOffSearch.partnerId" filterable placeholder="请选择供应商">
                    <el-option v-for="partner in partnerList" :key="partner.id" :label="partner.name" :value="partner.id"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="主体公司" prop="mainCompanyId">
                  <el-select v-model="writeOffSearch.mainCompanyId" placeholder="请选择主体公司">
                    <el-option v-for="company in companyList" :key="company.id" :label="company.name" :value="company.id"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="核销日期从" prop="startMakeDate">
                  <el-date-picker class="fsc-input" v-model="writeOffSearch.startMakeDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择核销开始日期"></el-date-picker>
                </el-form-item>

                <el-form-item label="核销日期到" prop="endMakeDate">
                  <el-date-picker class="fsc-input" v-model="writeOffSearch.endMakeDate" value-format="yyyy-MM-dd" type="date" placeholder="请选择核销结束日期"></el-date-picker>
                </el-form-item>

                <el-form-item label="会计期间" prop="fiscalPeriod">
                  <el-select v-model="writeOffSearch.fiscalPeriod" placeholder="请选择会计期间">
                    <el-option v-for="fiscalPeriod in fiscalPeriodList" :key="fiscalPeriod.id" :label="fiscalPeriod.name" :value="fiscalPeriod.id"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="币种" prop="currencyTypeId">
                  <el-select v-model="writeOffSearch.currencyTypeId" placeholder="请选择币种">
                    <el-option v-for="currencyType in currencyTypeList" :key="currencyType.id" :label="currencyType.name" :value="currencyType.id"></el-option>
                  </el-select>
                </el-form-item>

              </el-form>
            </el-main>
          </el-container>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="writeOffSearchClick">确定</el-button>
          </div>
        </el-dialog>

      </el-main>
    </el-container>

  </div>
</template>
<script>
import {
  addWriteOff,
  getWriteOff,
  updateWriteOff
} from '@/api/pay/writeOff'
import waves from '@/directive/waves' // 水波纹指令
import {
  getPartnerList,
  getCompanyList,
  getShouldPaymentTypeListByBusinessType,
  getCurrencyTypeList,
  getFiscalPeriodList,
  getShouldPaymentList,
  getPaymentList
} from '@/api/baseDataCommon'
export default {
  name: 'writeOffForm',
  directives: {
    waves
  },
  data() {
    return {
      dialogFormVisible: false,
      listLoading: false,
      writeOffForm: {
        borrowerWriteOffDetailList: [], // 借方
        lenderWriteOffDetailList: []  // 贷方
      },
      borrowerWriteOffDetailList: [], // 借方
      lenderWriteOffDetailList: [], // 贷方
      writeOffSearch: {},
      writeOffFormRules: {
        mainCompanyId: [{ required: true, message: '主体公司不能为空' }],
        docType: [{ required: true, message: '单据类型不能为空' }],
        docDate: [{ required: true, message: '单据日期不能为空' }],
        partnerId: [{ required: true, message: '供应商不能为空' }],
        fiscalPeriod: [{ required: true, message: '会计期间不能为空' }]
      },
      writeOffFormList: [],
      partnerList: [], // 供应商
      companyList: [], // 公司
      shouldPaymentTypeList: [],  // 应付单类型
      currencyTypeList: [],  // 币种
      fiscalPeriodList: [],  // 会计期间
      lenderFormList: [], // 贷方（应付单）
      borrowerFormList: [], // 借方(付款单)
      borrowerMoneyCount: 0, // 借方总金额
      lenderMoneyCount: 0 // 贷方总金额
    }
  },
  created() {
    // 获取供应商
    getPartnerList().then(result => {
      this.$data.partnerList = result.data
    })
    // 获取公司
    getCompanyList().then(result => {
      this.$data.companyList = result.data
    })
    // 应付单类型
    // TODO 业务类型 100
    getShouldPaymentTypeListByBusinessType(['100']).then(result => {
      this.$data.shouldPaymentTypeList = result.data
    })
    // 币种
    getCurrencyTypeList().then(result => {
      this.$data.currencyTypeList = result.data
    })
    // 获取会计期间
    getFiscalPeriodList().then(result => {
      this.$data.fiscalPeriodList = result.data
    })

    // 更新赋值新数据
    if (this.$route.params.data) {
      this.$data.writeOffForm = this.$route.params.data
      this.$data.borrowerWriteOffDetailList = this.$route.params.data.borrowerWriteOffDetailList
      this.$data.lenderWriteOffDetailList = this.$route.params.data.lenderWriteOffDetailList
    }
  },
  watch: {
    borrowerWriteOffDetailList: { // 借方金额监控
      handler(value, oldVaule) {
        this.$data.borrowerMoneyCount = 0
        value.forEach((v, i) => {
          this.$data.borrowerMoneyCount += parseFloat(v.writeOffAmountOc)
        })
        this.$data.borrowerMoneyCount = this.$data.borrowerMoneyCount.toFixed(2)
      },
      deep: true
    },
    lenderWriteOffDetailList: { // 贷方方金额监控
      handler(value, oldVaule) {
        this.$data.lenderMoneyCount = 0
        value.forEach((v, i) => {
          this.$data.lenderMoneyCount += parseFloat(v.writeOffAmountOc)
        })
        this.$data.lenderMoneyCount = this.$data.lenderMoneyCount.toFixed(2)
      },
      deep: true
    }
  },
  methods: {
    addWriteOffFormClick() {
      // 新增核销单
      this.$refs['writeOffForm'].validate(valid => {
        if (valid) {
          // 获取借方
          this.$data.writeOffForm.borrowerWriteOffDetailList = this.$refs.borrowerFormTable.data
          // 获取贷方
          this.$data.writeOffForm.lenderWriteOffDetailList = this.$refs.lenderFormTable.data
          addWriteOff(this.$data.writeOffForm).then(result => {
            // 清空数据
            this.$data.writeOffForm = {}
            this.$data.borrowerWriteOffDetailList = [] // 借方
            this.$data.lenderWriteOffDetailList = []  // 贷方
            if (result.code === 0) {
              this.$notify({
                title: '信息提示',
                message: '新增核销单成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '信息提示',
                message: result.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    updateWriteOffClick(id) {
      // 更新核销单 click
      getWriteOff(id).then(result => {
        if (result.code === 0) {
          this.$data.writeOff = result.data
        } else {
          this.$notify({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    updateWriteOffSubmit() {
      // 更新核销单 submit
      this.$refs['writeOffForm'].validate(valid => {
        if (valid) {
          updateWriteOff(this.$data.writeOff).then(result => {
            if (result.code === 0) {
              this.$data.dialogFormVisible = false
              this.$notify({
                title: '信息提示',
                message: '更新核销单类型成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '信息提示',
                message: result.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    closeDialogForm() { // 关闭 dialog
      this.$data.dialogFormVisible = false
    },
    getBorrowerAndLenderClick() { // 获取借贷方明细
      // 默认赋值表单 主体公司及供应商
      if (this.$data.writeOffForm.mainCompanyId) {
        this.$data.writeOffSearch.mainCompanyId = this.$data.writeOffForm.mainCompanyId
      }
      if (this.$data.writeOffForm.partnerId) {
        this.$data.writeOffSearch.partnerId = this.$data.writeOffForm.partnerId
      }
      this.$data.dialogFormVisible = true
    },
    writeOffSearchClick() { // 核销明细查询
      if (!this.$data.writeOffSearch.partnerId) {
        this.$notify({
          title: '信息提示',
          message: '请选择供应商',
          type: 'error',
          duration: 2000
        })
        return
      }

      if (!this.$data.writeOffSearch.mainCompanyId) {
        this.$notify({
          title: '信息提示',
          message: '请选择主体公司',
          type: 'error',
          duration: 2000
        })
        return
      }

      if (!this.$data.writeOffSearch.startMakeDate) {
        this.$notify({
          title: '信息提示',
          message: '请选择开始核销日期',
          type: 'error',
          duration: 2000
        })
        return
      }

      if (!this.$data.writeOffSearch.endMakeDate) {
        this.$notify({
          title: '信息提示',
          message: '请选择结束核销日期',
          type: 'error',
          duration: 2000
        })
        return
      }

      //  获取贷方（应付单）
      this.$data.writeOffSearch.businessTypeList = ['10', '30', '60'] // 业务类型
      getShouldPaymentList(this.$data.writeOffSearch).then(result => {
        if (result.code === 0) {
          this.$data.lenderWriteOffDetailList = []
          for (const index in result.data) {
            this.$data.lenderWriteOffDetailList.push({
              writeOffBtId: result.data[index].businessType,  // 业务类型
              writeOffDtId: result.data[index].docType, // 单据类型
              writeOffDtName: result.data[index].docTypeName, // 单击类型名称
              docCode: result.data[index].docCode, // 单据号
              money: result.data[index].originalCurrencyBalance,  // 可核销金额
              writeOffAmountOc: result.data[index].originalCurrencyBalance // 本次核销金额(默认等于可核销金额)
            })
          }

          // 获取借方 （付款单）
          this.$data.writeOffSearch.businessTypeList = ['20', '40', '70', '80'] // 业务类型
          getPaymentList(this.$data.writeOffSearch).then(writeOffResult => {
            if (writeOffResult.code === 0) {
              this.$data.borrowerWriteOffDetailList = []
              for (const index in writeOffResult.data) {
                this.$data.borrowerWriteOffDetailList.push({
                  writeOffBtId: writeOffResult.data[index].businessType,  // 业务类型
                  writeOffDtId: writeOffResult.data[index].docType, // 单据类型
                  writeOffDtName: writeOffResult.data[index].docTypeName, // 单击类型名称
                  docCode: writeOffResult.data[index].docCode, // 单据号
                  money: writeOffResult.data[index].originalCurrencyBalance,  // 可核销金额
                  writeOffAmountOc: writeOffResult.data[index].originalCurrencyBalance // 本次核销金额(默认等于可核销金额)
                })
              }
              this.$data.dialogFormVisible = false // 关闭dialog
            } else {
              this.$notify({
                title: '信息提示',
                message: writeOffResult.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        } else {
          this.$notify({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    removeBorrowerClick(index) { // 删除借方
      this.$data.borrowerWriteOffDetailList = this.$data.borrowerWriteOffDetailList.filter((v, i) => i !== index)
    },
    removeLenderClick(index) { // 删除贷方
      this.$data.lenderWriteOffDetailList = this.$data.lenderWriteOffDetailList.filter((v, i) => i !== index)
    }
  }
}
</script>
<style scoped>

</style>
